package com.generalbackend.common.util;

import com.generalbackend.common.model.entity.Property;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.ant.util.LinkedHashtable;

import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author tim.xie
 * @date 2021/12/14 18:29
 */
@Slf4j
public class PropertyManage extends LinkedHashtable<Object,Object> {

    protected PropertyManage defaults;

    public synchronized void load(BufferedReader reader) throws IOException {
        String line = "";
        while ((line=reader.readLine())!=null) {
            if (!line.trim().startsWith("#")) {
                int len = 0;
                char c;
                char[] bytes = line.toCharArray();
                while(true) {
                    c = bytes[len];
                    if(c == '=') {
                        String key = String.valueOf(bytes, 0, len);
                        String value = String.valueOf(bytes, len + 1,
                                bytes.length - String.valueOf(bytes, 0, len).length() - 1);
                        Property property = new Property(key, value);
                        put(key, property);
                        break;
                    }
                    len++;
                }
            }
        }
    }

    public Property getProperty(String key) {
        Object oval = super.get(key);
        Property sval = (oval instanceof Property) ? (Property) oval : null;
        return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
    }

}
